package com.nitty.cash.loop.ui.activity

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.os.CountDownTimer
import android.view.View
import com.nitty.cash.loop.R
import com.nitty.cash.loop.base.app.NittyStackManager
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.databinding.UiOrderPayPinBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.OrderPayPinPresenter
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/27 17:04
 * @Annotation：PIN 支付结果处理中
 */
class OrderPayPinAct: CommonActivity(),IViewContract.IOrderPayPinView {
    lateinit var binding: UiOrderPayPinBinding
    var presenter: OrderPayPinPresenter? = null
    //倒计时
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 30
    companion object {
        private const val INTENT_KEY_ORDER_ID = "orderId"
        private const val INTENT_KEY_THIRD_ORDER_ID = "thirdOrderId"
        fun start(context: Context, orderId: String, thirdOrderId: String) {
            val intent = Intent(context, OrderPayPinAct::class.java)
            intent.putExtra(INTENT_KEY_ORDER_ID, orderId)
            intent.putExtra(INTENT_KEY_THIRD_ORDER_ID,thirdOrderId)
            context.startActivity(intent)
        }
    }

    override fun getNittyRootView(): View? {
        binding = UiOrderPayPinBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        setNittyRootParentBackgroundColor(Color.parseColor("#FFFAF9F9"))
        setNittyTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setNittyBackBtnRes(R.mipmap.img_back_black)
        setNittyRightBtnRes(R.mipmap.img_customer_black)
        setNittyTextTitle(getString(R.string.loan_payment_status_title))
        initOrderPinRefrashView()
        binding.pinStatusLayout.visibility = View.INVISIBLE
    }

    override fun initNittyListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Pin Payment Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"Pin Payment Page")
        }
        //订单号复制
        binding.imgOrderIdCopy.setOnClickListener {
            onOrderIdCopyAction(presenter!!.getThirdOrderId())
        }
        //还款中 刷新
        binding.orderPinRefreshLayout.setOnClickListener {
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOAN_PIN_PROCESS_PAYMENT_UPDATE,"TransactionId：${presenter?.getThirdOrderId()}")
            presenter?.getNittyOrderPayPinStatusAction()
        }
        //成功 - 再次申请
        binding.pinSuccessApplyAgain.setOnClickListener {
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOAN_PIN_SUCCESS_APPLY_AGAIN,"TransactionId：${presenter?.getThirdOrderId()}")
            showOrderPaySuccessAction()
        }
        //失败 - 重新发起支付
        binding.pinFailedAgain.setOnClickListener {
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOAN_PIN_FAILED_PAYMENT_AGAIN,"TransactionId：${presenter?.getThirdOrderId()}")
            presenter?.getNittyOrderPayAction()
        }
        //还款中 - 重新发起支付
        binding.pinProcessAgain.setOnClickListener {
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOAN_PIN_PROCESS_PAYMENT_AGAIN,"TransactionId：${presenter?.getThirdOrderId()}")
            presenter?.getNittyOrderPayAction()
        }
    }

    override fun loadNittyData() {
        if (presenter == null){
            presenter = OrderPayPinPresenter(this)
        }
        presenter?.saveOrderPayPinThirdOrderId(getOrderPayThirdOrderId())
        presenter?.getNittyOrderPayPinStatusAction()
    }

    /* 初始化刷新 */
    private fun initOrderPinRefrashView() {
        binding.pinRefreshView.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.pinRefreshView.setOnRefreshListener {
            presenter?.getNittyOrderPayPinStatusAction()
        }
    }


    /**
     * 支付成功 - 跳转到可申请列表
     */
    private fun showOrderPaySuccessAction(){
        //刷新流程
        publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESH))
        //返回首页
        publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_SHOW_HOME))
        NittyStackManager.finishAllActivity(NittyTabAct::class.java)
    }

    /**
     * 获取订单id
     */
    override fun getNittyPayPinOrderId(): String {
        if (intent.extras == null){
            return ""
        }
        return intent.extras?.getString(INTENT_KEY_ORDER_ID).toString()
    }

    /**
     * 三方订单id
     */
    private fun getOrderPayThirdOrderId(): String {
        if (intent.extras == null){
            return ""
        }
        return intent.extras?.getString(INTENT_KEY_THIRD_ORDER_ID).toString()
    }

    /**
     * PIN 通用View
     */
    override fun showNittyPayPinCommonView(data: JSONObject) {
        binding.textAmount.text = data.optString("realRepayAmount","")
//        binding.textUnit.text = data.optString("")
        binding.textUnit.visibility = View.GONE
        binding.textProduct.text = data.optString("product","")
        binding.textOrderId.text = data.optString("transactionId","")
        binding.pinStatusLayout.visibility = View.VISIBLE
    }

    /**
     * PIN 支付成功
     */
    override fun showNittyPayPinSuccessView(data: JSONObject) {
        binding.imgPayPinStatus.setImageResource(R.mipmap.nitty_apply_rejected_icon)
        binding.orderPinRefreshLayout.isEnabled = false
        binding.imgOrderPinRefreshView.visibility = View.GONE
        binding.textOrderPinStatus.text = getString(R.string.loan_payment_status_success_awesome)
        binding.textOrderPinStatus.paint.flags = Paint.ANTI_ALIAS_FLAG
        binding.textOrderPinMsg.visibility = View.VISIBLE
        binding.textOrderPinMsg.text = getString(R.string.loan_payment_status_success_tips)
        binding.orderIdLayout.visibility = View.VISIBLE

        binding.pinProcessLayout.visibility = View.GONE
        binding.pinSuccessLayout.visibility = View.VISIBLE
        binding.pinFailedLayout.visibility = View.GONE

        binding.pinPaySuccessTime.text = data.optString("realRepayTime","")

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * PIN 支付失败
     */
    override fun showNittyPayPinFailedView(data: JSONObject) {
        binding.imgPayPinStatus.setImageResource(R.mipmap.nitty_apply_rejected_icon)
        binding.orderPinRefreshLayout.isEnabled = false
        binding.imgOrderPinRefreshView.visibility = View.GONE
        binding.textOrderPinStatus.text = getString(R.string.loan_payment_status_failed_title)
        binding.textOrderPinStatus.paint.flags = Paint.ANTI_ALIAS_FLAG
        val failReason = data.optString("failReason","")
        if (failReason.isNotEmpty()){
            binding.textOrderPinMsg.visibility = View.VISIBLE
            binding.textOrderPinMsg.text = String.format(getString(R.string.loan_payment_status_failed_tips),failReason)
        } else {
            binding.textOrderPinMsg.visibility = View.GONE
        }
        binding.orderIdLayout.visibility = View.VISIBLE

        binding.pinProcessLayout.visibility = View.GONE
        binding.pinSuccessLayout.visibility = View.GONE
        binding.pinFailedLayout.visibility = View.VISIBLE

        binding.orderPayFailedTime.text = data.optString("failedTime","")

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * PIN 支付中
     */
    override fun showNittyPayPinProcessView(data: JSONObject) {
        //是否是审核账号
        val isConfigAccount = NittySharedHelper.getNittySharedBoolean(NittySharedKey.NITTY_IS_CONFIG_ACCOUNT)
        if(isConfigAccount) {//审核账号，直接进入还款失败
            showNittyPayPinFailedView(data)
            return
        }
        binding.imgPayPinStatus.setImageResource(R.mipmap.nitty_order_details_inreviewing_icon)
        binding.orderPinRefreshLayout.isEnabled = true
        binding.imgOrderPinRefreshView.visibility = View.VISIBLE
        binding.textOrderPinStatus.text = getString(R.string.loan_payment_status_update)
        binding.textOrderPinStatus.paint.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
        binding.textOrderPinStatus.paint.isAntiAlias = true//抗锯齿
        binding.textOrderPinMsg.visibility = View.GONE
        binding.orderIdLayout.visibility = View.GONE

        binding.pinProcessLayout.visibility = View.VISIBLE
        binding.pinSuccessLayout.visibility = View.GONE
        binding.pinFailedLayout.visibility = View.GONE

        binding.orderPayProcessReason.text = String.format(getString(R.string.loan_payment_status_processed_reason1),data.optString("realRepayAmount",""))

        countdown = 0
        showPinProcessStatus()
        //是否开启倒计时
        if (data.optBoolean("isStartCountdown",true)){
            startCountdownTimer()
        }
    }

    /**
     * 开启倒计时
     */
    private fun startCountdownTimer(){
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        countdown = 30

        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val act: OrderPayPinAct,millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showPinProcessStatus()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.presenter?.getNittyOrderPayPinStatusAction(false)
        }
    }

    /**
     * 设置按钮状态
     */
    private fun showPinProcessStatus(){
        if (countdown <= 0){
            binding.pinProcessAgain.isEnabled = true
            binding.pinProcessAgain.text = String.format(getString(R.string.loan_payment_status_make_payment_again),"")
        } else {
            binding.pinProcessAgain.isEnabled = false
            binding.pinProcessAgain.text = String.format(getString(R.string.loan_payment_status_make_payment_again),"(${countdown}s)")
        }
    }

    /**
     * 复制
     */
    private fun onOrderIdCopyAction(orderId: String){
        addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOAN_PIN_ORDER_ID_COPY, "TransactionId：$orderId")
        // 获取剪贴板管理器
        val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个 ClipData 对象，将要复制的文本放入其中
        val clipData = ClipData.newPlainText("label", orderId)
        // 将 ClipData 对象放入剪贴板
        clipboardManager.setPrimaryClip(clipData)
        showNittyToast(getString(R.string.customer_email_copy_success))
    }

    override fun hiddenNittyLoading() {
        super.hiddenNittyLoading()
        binding.pinRefreshView.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_LOAN_PIN_REPAYMENT_START,"TransactionId：${getOrderPayThirdOrderId()}")
    }

    override fun onDestroy() {
        super.onDestroy()
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_LOAN_PIN_REPAYMENT_END,"TransactionId：${presenter!!.getThirdOrderId()}")
    }
}